import { useEffect, useState, useContext } from "react";
import { getGlobalValue, getSettingsDefault, getBlocksDefault } from "@/tool/settingConfigFilter";
import { Button } from "@arco-design/web-react";

import html2canvas from "html2canvas";
export default function () {
    let currentSection = {};
    const pageSectionIds = [];
    function setProperty(global, parentKey = "") {
        const root = document.documentElement;
        Object.keys(global).forEach((key) => {
            // 设置CSS变量的值
            if (typeof global[key] === "object" && global[key] !== null) {
                setProperty(global[key], `${key}_`);
            } else {
                let unit = "";
                if (
                    [
                        "general_layout_width",
                        "general_layout_spacing",
                        "popup_border_radius",
                        "button_border_radius",
                        "full_container_padding",
                        "general_font_size",
                        "product_font_size",
                        "title_font_size",
                        "big_product_font_size",
                        "title_letter_spacing",
                        "nav_letter_spacing"
                    ].includes(key)
                ) {
                    unit = "px";
                }

                root.style.setProperty(`--${parentKey}${key}`, global[key] + unit);
            }
        });
    }

    // function handleUploadImage() {
    //     html2canvas(document.querySelector("#sections-box"), {
    //         allowTaint: true,
    //         useCORS: true
    //     }).then((canvas) => {
    //         let img = document.createElement("a");
    //         img.href = canvas.toDataURL("image/jpeg").replace("image/jpeg", "image/octet-stream");
    //         img.download = `${current.template}_${current.section}.jpg`;
    //         img.click();
    //     });
    // }

    function updateSections(id, html, section) {
        if (section === "header") {
            $("#card-header").html(html);
            return;
        }

        if (section === "footer") {
            $("#card-footer").html(html);
            return;
        }

        if (!pageSectionIds.includes(id)) {
            pageSectionIds.push(id);
            $("#MainContent").append(`<div id="sections-item-${id}">${html}</div>`);
        } else {
            $("#sections-item-" + id).html(html);
        }
    }

    useEffect(() => {
        window["oemcart_platform"] = "1";
        window.addEventListener("message", function (res) {
            if (res.data.origin === "moi" && res.data.type === "image") {
                currentSection = res.data.data;
                const global = getGlobalValue(currentSection.global);
                setProperty(global);
                fetch(`http://localhost:3030/api/render/${currentSection.template}/block/${currentSection.section}`, {
                    method: "post",
                    headers: {
                        "Content-Type": "application/json"
                    },
                    body: JSON.stringify({
                        default: {
                            type: currentSection.section,
                            block_id: new Date().getTime(),
                            settings: getSettingsDefault(currentSection.settings),
                            blocks: getBlocksDefault(currentSection.blocks)
                        },
                        theme_config: { global }
                    })
                })
                    .then((data) => data.json())
                    .then((res) => {
                        if (res.code === 200) {
                            updateSections(currentSection.id, res.data.html, currentSection.section);
                            return
                            const link = document.createElement("link");
                            link.rel = "stylesheet";
                            link.type = "text/css";
                            link.href = res.data.link;
                            link.onload = function () {
                                updateSections(currentSection.id, res.data.html, currentSection.section);
                            };
                            document.head.appendChild(link);
                        }
                    });
            }
        });
    }, []);
    return (
        <div className="py-5">
            <header id="card-header"> </header>
            <div className="main-content" id="MainContent"></div>
            <footer id="card-footer"></footer>
            {/* <div id="sections-box"></div> */}
            {/* <div onClick={handleUploadImage}>下周图片</div> */}
        </div>
    );
}
